#include "audiocapture.h"

AudioCapture::AudioCapture(QObject *parent)
    : QObject(parent),
      audioInput(nullptr),
      quality(2),
      sampleRate(44100), // 默认采样率44.1KHz
      channelCount(2),   // 默认双声道
      sampleSize(16),    // 默认16位
      capturing(false)
{
    // 初始化音频格式
    initAudioFormat();
    
    // 初始化数据读取定时器
    dataTimer.setInterval(100); // 每100ms读取一次数据
    connect(&dataTimer, &QTimer::timeout, this, &AudioCapture::readAudioData);
    
    // 初始化缓冲区
    audioBuffer.open(QIODevice::ReadWrite);
    
    LOG_INFO("音频捕获模块已初始化");
}

AudioCapture::~AudioCapture()
{
    stop();
    
    if (audioInput) {
        delete audioInput;
        audioInput = nullptr;
    }
    
    LOG_INFO("音频捕获模块已销毁");
}

bool AudioCapture::start()
{
    if (capturing) {
        LOG_WARNING("音频捕获已经在进行中");
        return true;
    }
    
    if (!selectAudioDevice()) {
        emit errorOccurred("无法找到合适的音频输入设备");
        return false;
    }
    
    // 重置缓冲区
    audioBuffer.buffer().clear();
    audioBuffer.seek(0);
    
    // 创建音频输入对象
    if (audioInput) {
        delete audioInput;
    }
    
    audioInput = new QAudioInput(inputDevice, audioFormat, this);
    
    // 开始录音
    audioInput->start(&audioBuffer);
    
    if (audioInput->state() != QAudio::ActiveState) {
        LOG_ERROR("无法开始音频捕获");
        emit errorOccurred("无法开始音频捕获");
        delete audioInput;
        audioInput = nullptr;
        return false;
    }
    
    capturing = true;
    dataTimer.start();
    
    LOG_INFO("音频捕获已开始");
    return true;
}

void AudioCapture::stop()
{
    if (!capturing) {
        return;
    }
    
    dataTimer.stop();
    
    if (audioInput) {
        audioInput->stop();
        delete audioInput;
        audioInput = nullptr;
    }
    
    capturing = false;
    
    LOG_INFO("音频捕获已停止");
}

bool AudioCapture::isCapturing() const
{
    return capturing;
}

void AudioCapture::setQuality(int quality)
{
    if (quality < 1) quality = 1;
    if (quality > 3) quality = 3;
    
    this->quality = quality;
    
    // 根据质量设置采样率和通道数
    switch (quality) {
    case 1: // 低质量
        sampleRate = 22050;
        channelCount = 1;
        break;
    case 2: // 中质量
        sampleRate = 44100;
        channelCount = 2;
        break;
    case 3: // 高质量
        sampleRate = 48000;
        channelCount = 2;
        break;
    }
    
    // 更新音频格式
    initAudioFormat();
    
    LOG_INFO(QString("音频质量已设置为: %1").arg(quality));
}

int AudioCapture::getQuality() const
{
    return quality;
}

void AudioCapture::setSampleRate(int sampleRate)
{
    this->sampleRate = sampleRate;
    initAudioFormat();
    
    LOG_INFO(QString("音频采样率已设置为: %1").arg(sampleRate));
}

int AudioCapture::getSampleRate() const
{
    return sampleRate;
}

void AudioCapture::setChannelCount(int channelCount)
{
    this->channelCount = channelCount;
    initAudioFormat();
    
    LOG_INFO(QString("音频通道数已设置为: %1").arg(channelCount));
}

int AudioCapture::getChannelCount() const
{
    return channelCount;
}

void AudioCapture::readAudioData()
{
    if (!capturing || !audioInput) {
        return;
    }
    
    // 获取缓冲区中的数据大小
    qint64 bytesReady = audioBuffer.bytesAvailable();
    
    if (bytesReady <= 0) {
        return;
    }
    
    // 读取数据
    QByteArray audioData = audioBuffer.read(bytesReady);
    
    if (!audioData.isEmpty()) {
        emit audioDataAvailable(audioData);
    }
    
    // 如果缓冲区已满，重置缓冲区
    if (audioBuffer.size() > 1024 * 1024) { // 超过1MB
        audioBuffer.buffer().clear();
        audioBuffer.seek(0);
    }
}

void AudioCapture::initAudioFormat()
{
    audioFormat.setSampleRate(sampleRate);
    audioFormat.setChannelCount(channelCount);
    audioFormat.setSampleSize(sampleSize);
    audioFormat.setCodec("audio/pcm");
    audioFormat.setByteOrder(QAudioFormat::LittleEndian);
    audioFormat.setSampleType(QAudioFormat::SignedInt);
}

bool AudioCapture::selectAudioDevice()
{
    QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
    
    if (devices.isEmpty()) {
        LOG_ERROR("没有可用的音频输入设备");
        return false;
    }
    
    // 检查默认设备是否支持我们的格式
    QAudioDeviceInfo defaultDevice = QAudioDeviceInfo::defaultInputDevice();
    if (defaultDevice.isFormatSupported(audioFormat)) {
        inputDevice = defaultDevice;
        LOG_INFO(QString("使用默认音频输入设备: %1").arg(defaultDevice.deviceName()));
        return true;
    }
    
    // 尝试其他设备
    for (const QAudioDeviceInfo &device : devices) {
        if (device.isFormatSupported(audioFormat)) {
            inputDevice = device;
            LOG_INFO(QString("使用音频输入设备: %1").arg(device.deviceName()));
            return true;
        }
    }
    
    // 如果没有找到支持的设备，使用最接近的格式
    inputDevice = QAudioDeviceInfo::defaultInputDevice();
    audioFormat = inputDevice.nearestFormat(audioFormat);
    sampleRate = audioFormat.sampleRate();
    channelCount = audioFormat.channelCount();
    sampleSize = audioFormat.sampleSize();
    
    LOG_WARNING(QString("没有完全匹配的设备，使用最接近的音频格式: 采样率=%1, 通道数=%2, 采样位数=%3")
               .arg(sampleRate).arg(channelCount).arg(sampleSize));
    
    return true;
} 